package main

import (
	"bufio"
	"fmt"
	"gitee.com/sugarcoder/leetcode-go/tree"
	"os"
	"strconv"
	"strings"
)

func help_msg() {
	fmt.Println("Red(1) Black(0) Tree commands:")
	fmt.Println("h: print this message")
	fmt.Println("i value: insert value")
	fmt.Println("d value: delete value")
	fmt.Println("q: quit")
	fmt.Println("p: print level order tree")
}

func main() {
	rbtree := tree.NewRBTree()
	scanner := bufio.NewScanner(os.Stdin)
	fmt.Print(">")
OUTER:
	for scanner.Scan() {
		input := scanner.Text()
		args := strings.Split(input, " ")
		switch args[0] {
		case "i":
			if len(args) < 2 {
				help_msg()
			} else {
				if val, err := strconv.Atoi(args[1]); err == nil {
					rbtree.RBInsert(val)
				} else {
					fmt.Println("Cannot parse inserted value")
				}
			}
		case "d":
			if len(args) < 2 {
				help_msg()
			} else {
				if val, err := strconv.Atoi(args[1]); err == nil {
					if rbtree.RBDelete(val) {
						rbtree.LevelOrderTraversalPrint()
					} else {
						fmt.Println("Value not exist")
					}
				} else {
					fmt.Println("Cannot parse deleted value")
				}
			}
		case "p":
			rbtree.LevelOrderTraversalPrint()
		case "h":
			help_msg()
		case "q":
			break OUTER
		default:
			help_msg()
		}
		fmt.Print(">")
	}
}
